// 音乐相关元素与状态
const bgMusic = document.getElementById('bgMusic');
const musicToggle = document.querySelector('.music-toggle');
const musicIcon = document.getElementById('musicIcon');
let isMusicOn = false;

// 音乐开关事件
musicToggle.addEventListener('click', function () {
  if (isMusicOn) {
    bgMusic.pause();
    musicIcon.textContent = "▶️";
    musicToggle.classList.remove('playing');
  } else {
    bgMusic.play()
      .then(() => {
        musicIcon.textContent = "⏸️";
        musicToggle.classList.add('playing');
      })
      .catch(err => {
        alert('浏览器禁止自动播放音乐，请点击页面后再次尝试开启~');
      });
  }
  isMusicOn = !isMusicOn;
  localStorage.setItem('bgMusicStatus', isMusicOn);
});


// 全局错题记录
let wrongQuestionList = [];

// 页面加载初始化（用户记录相关）
window.addEventListener('load', function () {
  const userRecords = JSON.parse(localStorage.getItem('userRecords') || '[]');
  const userInput = document.querySelector('#username-input');
  const inputUserName = document.querySelector('#input-username');

  if (userRecords.length > 0) {
    const latestUser = userRecords[userRecords.length - 1];
    userInput.value = latestUser;
    inputUserName.innerHTML = latestUser;
  }
});


// 用户名提交与游戏引导页逻辑
let userInput = document.querySelector('#username-input');
let startBtn = document.querySelector('#start')
let uname = document.querySelector('.uname')
let guide = document.querySelector('.game-guide')
let inputUserName = document.querySelector('#input-username')
let submitBtnFill = document.querySelector('.submit-btn-fill')
submitBtnFill.style.display = 'none'

// 开始按钮点击事件（用户名确认）
startBtn.addEventListener('click', function () {
  const username = userInput.value.trim();
  if (username === '') {
    alert('用户名不能为空')
    return;
  }

  const userRecords = JSON.parse(localStorage.getItem('userRecords') || '[]');
  const filteredRecords = userRecords.filter(user => user !== username);
  filteredRecords.push(username);

  localStorage.setItem('userRecords', JSON.stringify(filteredRecords));
  inputUserName.innerHTML = username;

  uname.style.display = 'none';
  guide.style.display = 'block';
});


// 游戏说明页到答题页的跳转
let startGame = document.querySelector('#start-game')
let gameGuide = document.querySelector('.game-guide')
let box = document.querySelector('.box')
startGame.addEventListener('click', function () {
  gameGuide.style.display = 'none';
  box.style.display = 'block';

  const userRecords = JSON.parse(localStorage.getItem('userRecords') || '[]');
  if (userRecords.length > 0) {
    inputUserName.innerHTML = userRecords[userRecords.length - 1];
  }
});


// 选择题相关元素与逻辑
let choiseText = document.querySelector('.choise-text');
let optA = document.querySelector('.optA')
let optB = document.querySelector('.optB')
let optC = document.querySelector('.optC')
let optD = document.querySelector('.optD')

// 选择题状态变量
let usedWordIndexes = [];
let choiceQuestions = [];
let currentQuestionIndex = 0;
let correctAnswer = '';
let score = document.querySelector('#scoreNum')

// 随机获取不重复元素工具函数
function getRandomUniqueItems(arr, count) {
  const result = [];
  const tempArr = [...arr];
  while (result.length < count && tempArr.length > 0) {
    const randomIndex = Math.floor(Math.random() * tempArr.length);
    result.push(tempArr.splice(randomIndex, 1)[0]);
  }
  return result;
}

// 生成选择题题库
function generateChoiceQuestions() {
  while (choiceQuestions.length < 10) {
    let randomWord;
    do {
      const randomIndex = Math.floor(Math.random() * wordData.length);
      randomWord = wordData[randomIndex];
    } while (usedWordIndexes.includes(wordData.indexOf(randomWord)));

    usedWordIndexes.push(wordData.indexOf(randomWord));

    const allOtherWords = wordData.filter(word => word !== randomWord);
    const distractorWords = getRandomUniqueItems(allOtherWords, 3);

    const allOptions = [
      { text: randomWord.english, isCorrect: true },
      { text: distractorWords[0].english, isCorrect: false },
      { text: distractorWords[1].english, isCorrect: false },
      { text: distractorWords[2].english, isCorrect: false }
    ].sort(() => Math.random() - 0.5);

    choiceQuestions.push({
      question: `“${randomWord.chinese}”对应的英文是？`,
      options: allOptions,
      correctEnglish: randomWord.english
    });
  }
}

// 渲染当前选择题
function renderCurrentChoiceQuestion() {
  document.querySelector('.choice-question').style.display = 'block';
  document.querySelector('.fill-question').style.display = 'none';
  document.querySelector('.complete-question').style.display = 'none';

  const currentQuestion = choiceQuestions[currentQuestionIndex];
  document.querySelector('.choiseText').textContent = currentQuestion.question;

  const options = document.querySelectorAll('.option');
  options.forEach((option, index) => {
    option.textContent = `${String.fromCharCode(65 + index)}. ${currentQuestion.options[index].text}`;
    option.dataset.isCorrect = currentQuestion.options[index].isCorrect;
    option.classList.remove('selected');
  });

  correctAnswer = currentQuestion.correctEnglish;
}

// 初始化选择题游戏
function initChoiceGame() {
  usedWordIndexes = [];
  choiceQuestions = [];
  currentQuestionIndex = 0;

  generateChoiceQuestions();
  renderCurrentChoiceQuestion();

  // 选择题倒计时
  function startCountdown() {
    let time = 30;
    const timerEl = document.querySelector('#timeRemaining');
    timerEl.innerHTML = time;

    if (window.countdownTimer) clearInterval(window.countdownTimer);

    window.countdownTimer = setInterval(() => {
      time--;
      timerEl.innerHTML = time;
      if (time <= 0) {
        clearInterval(window.countdownTimer);
        alert(`时间到！正确答案是：${correctAnswer}`);
        wrongQuestionList.push({
          type: "选择题",
          question: choiceQuestions[currentQuestionIndex].question,
          userAnswer: "未作答（超时）",
          correctAnswer: correctAnswer
        });
        currentQuestionIndex++;
        if (currentQuestionIndex < choiceQuestions.length) {
          renderCurrentChoiceQuestion();
          startCountdown();
        } else {
          clearInterval(window.countdownTimer);
          alert('已完成！即将进入下一题型');
          document.querySelector('.choice-question').style.display = 'none';
          document.querySelector('.fill-question').style.display = 'block';
          document.querySelector('.complete-question').style.display = 'none';
          score.innerHTML = 0;
        }
      }
    }, 1000);
  }

  startCountdown();

  // 选项点击事件
  const options = document.querySelectorAll('.option');
  options.forEach(option => {
    option.addEventListener('click', function () {
      options.forEach(opt => opt.classList.remove('selected'));
      this.classList.add('selected');
    });
  });

  // 选择题提交按钮事件
  let submitBtnSelect = document.querySelector('.submit-btn button')
  submitBtnSelect.addEventListener('click', function () {
    const selectedOption = document.querySelector('.option.selected');
    if (!selectedOption) {
      alert('请选择一个选项！');
      return;
    }

    if (window.countdownTimer) clearInterval(window.countdownTimer);

    const isCorrect = selectedOption.dataset.isCorrect === 'true';
    if (isCorrect) {
      let addScore = (currentQuestionIndex >= 3 && currentQuestionIndex % 4 === 3) ? 5 : 3;
      let currentScore = parseInt(score.innerHTML) + addScore;
      score.innerHTML = currentScore;

      const currentUsername = document.querySelector('#input-username').textContent.trim();
      const scoreRecords = JSON.parse(localStorage.getItem('userScores') || '{}');
      const totalScore = (scoreRecords[currentUsername]?.totalScore || 0) + addScore;
      scoreRecords[currentUsername] = {
        choiceScore: currentScore,
        totalScore: totalScore,
        lastUpdate: new Date().toLocaleString()
      };
      localStorage.setItem('userScores', JSON.stringify(scoreRecords));
    } else {
      alert(`回答错误！正确答案是：${correctAnswer}`);
      wrongQuestionList.push({
        type: "选择题",
        question: choiceQuestions[currentQuestionIndex].question,
        userAnswer: selectedOption.textContent.split(". ")[1],
        correctAnswer: correctAnswer
      });
    }

    currentQuestionIndex++;
    if (currentQuestionIndex < choiceQuestions.length) {
      renderCurrentChoiceQuestion();
      startCountdown();
    } else {
      alert('已完成！即将进入下一题型');
      document.querySelector('.choice-question').style.display = 'none';
      document.querySelector('.fill-question').style.display = 'block';
      document.querySelector('.complete-question').style.display = 'none';
      document.querySelector('.submit-btn').style.display = 'none';
      document.querySelector('.submit-btn-fill').style.display = 'block';
      score.innerHTML = 0;

      generateFillQuestions();
      renderCurrentFillQuestion();
    }
  });
}

// 开始挑战按钮绑定（初始化选择题）
document.querySelector('#start-game').addEventListener('click', function () {
  gameGuide.style.display = 'none';
  box.style.display = 'block';

  const userRecords = JSON.parse(localStorage.getItem('userRecords') || '[]');
  if (userRecords.length > 0) {
    inputUserName.innerHTML = userRecords[userRecords.length - 1];
  }

  initChoiceGame();
});


// 填空题相关逻辑
let fillQuestion = document.querySelector('.fill-question')
let fillText = document.querySelector('.fillText')
let fillInput = document.querySelector('.fill-input')

// 填空题状态变量
let userWordIndexsFill = [];
let fillQuestions = [];
let currentQuestionIndexFill = 0;
let correctAnswerFill = '';

// 生成填空题题库
function generateFillQuestions() {
  while (fillQuestions.length < 10) {
    let randomWord;
    do {
      const randomIndex = Math.floor(Math.random() * wordData.length);
      randomWord = wordData[randomIndex];
    } while (usedWordIndexes.includes(wordData.indexOf(randomWord)) || userWordIndexsFill.includes(wordData.indexOf(randomWord)));

    userWordIndexsFill.push(wordData.indexOf(randomWord));
    fillQuestions.push({
      question: `“${randomWord.chinese}”对应的英文单词是？`,
      correctEnglish: randomWord.english.toLowerCase()
    });
  }
}

// 渲染当前填空题
function renderCurrentFillQuestion() {
  fillInput.value = '';
  const currentQuestion = fillQuestions[currentQuestionIndexFill];
  fillText.textContent = currentQuestion.question;
  correctAnswerFill = currentQuestion.correctEnglish;
  startFillCountdown();
}

// 填空题倒计时
function startFillCountdown() {
  let time = 30;
  const timerEl = document.querySelector('#timeRemaining');
  timerEl.innerHTML = time;

  if (window.fillCountdownTimer) clearInterval(window.fillCountdownTimer);

  window.fillCountdownTimer = setInterval(() => {
    time--;
    timerEl.innerHTML = time;
    if (time <= 0) {
      clearInterval(window.fillCountdownTimer);
      alert(`时间到！正确答案是：${correctAnswerFill}`);
      wrongQuestionList.push({
        type: "填空题",
        question: fillQuestions[currentQuestionIndexFill].question,
        userAnswer: "未作答（超时）",
        correctAnswer: correctAnswerFill
      });
      nextFillQuestion();
    }
  }, 1000);
}

// 填空题下一题
function nextFillQuestion() {
  if (window.fillCountdownTimer) clearInterval(window.fillCountdownTimer);
  currentQuestionIndexFill++;
  if (currentQuestionIndexFill < fillQuestions.length) {
    renderCurrentFillQuestion();
  } else {
    alert('填空题已完成！即将进入补全题');
    document.querySelector('.fill-question').style.display = 'none';
    document.querySelector('.complete-question').style.display = 'block';
    score.innerHTML = 0;
    document.querySelector('#timeRemaining').innerHTML = 30;
    generateCompleteQuestions();
    renderCompleteQ();
  }
}

// 填空题提交按钮事件
document.querySelector('.submit-btn-fill button').addEventListener('click', function () {
  const userAnswer = fillInput.value.trim().toLowerCase();
  if (userAnswer === '') {
    alert('请输入答案后提交！');
    return;
  }

  if (window.fillCountdownTimer) clearInterval(window.fillCountdownTimer);

  let isCorrect = userAnswer === correctAnswerFill;
  if (isCorrect) {
    let addScore = (currentQuestionIndexFill >= 3 && currentQuestionIndexFill % 4 === 3) ? 5 : 3;
    let currentScore = parseInt(score.innerHTML) + addScore;
    score.innerHTML = currentScore;

    const currentUsername = document.querySelector('#input-username').textContent.trim();
    const scoreRecords = JSON.parse(localStorage.getItem('userScores') || '{}');
    scoreRecords[currentUsername] = {
      ...scoreRecords[currentUsername],
      fillScore: currentScore,
      totalScore: (scoreRecords[currentUsername]?.choiceScore || 0) + currentScore,
      lastUpdate: new Date().toLocaleString()
    };
    localStorage.setItem('userScores', JSON.stringify(scoreRecords));

    alert('回答正确！');
  } else {
    alert(`回答错误！正确答案是：${correctAnswerFill}`);
    wrongQuestionList.push({
      type: "填空题",
      question: fillQuestions[currentQuestionIndexFill].question,
      userAnswer: userAnswer,
      correctAnswer: correctAnswerFill
    });
  }

  nextFillQuestion();
});


// 补全题相关逻辑
let completeQuestion = document.querySelector('.complete-question')
let completeText = document.querySelector('.completeText')
let completeInput = document.querySelector('.complete-input')
let submitBtnComplete = document.querySelector('.submit-btn-complete')

// 补全题状态变量
let userWordIndexsComplete = [];
let completeQuestions = [];
let currentQuestionIndexComplete = 0;
let correctAnswerComplete = '';

// 生成补全题题库
function generateCompleteQuestions() {
  while (completeQuestions.length < 10) {
    let randomWord;
    do {
      const idx = Math.floor(Math.random() * wordData.length);
      randomWord = wordData[idx];
    } while (
      usedWordIndexes.includes(wordData.indexOf(randomWord)) ||
      userWordIndexsFill.includes(wordData.indexOf(randomWord)) ||
      userWordIndexsComplete.includes(wordData.indexOf(randomWord))
    );
    userWordIndexsComplete.push(wordData.indexOf(randomWord));

    const eng = randomWord.english.toLowerCase();
    const hideCount = eng.length > 3 ? 3 : 2;
    const hidePositions = []; // 存储需要隐藏的位置（排序后）

    // 随机选择要隐藏的位置并排序，确保输入框顺序与字母位置一致
    while (hidePositions.length < hideCount) {
      const pos = Math.floor(Math.random() * eng.length);
      if (!hidePositions.includes(pos)) {
        hidePositions.push(pos);
      }
    }
    hidePositions.sort((a, b) => a - b); // 按字母位置排序

    // 构建题目文本
    let qText = "";
    for (let i = 0; i < eng.length; i++) {
      qText += hidePositions.includes(i) ? "__ " : eng[i] + " ";
    }

    completeQuestions.push({
      question: `“${randomWord.chinese}”：${qText}（补全缺失字母）`,
      fullWord: eng, // 完整单词
      blankCount: hideCount,
      blanks: hidePositions.map(pos => ({
        position: pos,       // 字母在单词中的位置
        correctChar: eng[pos] // 该位置的正确字母
      }))
    });
  }
}

// 渲染补全题
function renderCompleteQ() {
  const currQ = completeQuestions[currentQuestionIndexComplete];
  completeText.textContent = currQ.question;

  const container = document.querySelector('.complete-inputs');
  container.innerHTML = ''; // 清空容器

  // 创建与空数量相同的输入框（按位置顺序）
  currQ.blanks.forEach((blank, i) => {
    const input = document.createElement('input');
    input.className = 'complete-input';
    input.maxLength = 1;
    input.placeholder = `第${i + 1}空`;
    input.dataset.blankIndex = i; // 记录这是第几个空
    container.appendChild(input);
  });

  // 添加提交按钮
  container.appendChild(submitBtnComplete);

  startCompleteTimer();
}

// 补全题倒计时
function startCompleteTimer() {
  let time = 30;
  const timerEl = document.querySelector('#timeRemaining');
  timerEl.innerHTML = time;

  clearInterval(window.completeTimer);
  window.completeTimer = setInterval(() => {
    time--;
    timerEl.innerHTML = time;
    if (time <= 0) {
      clearInterval(window.completeTimer);
      alert(`超时！正确答案：${correctAnswerComplete}`);
      wrongQuestionList.push({
        type: "补全题",
        question: completeQuestions[currentQuestionIndexComplete].question,
        userAnswer: "未作答（超时）",
        correctAnswer: correctAnswerComplete
      });
      nextCompleteQ();
    }
  }, 1000);
}

// 补全题下一题
function nextCompleteQ() {
  clearInterval(window.completeTimer);
  currentQuestionIndexComplete++;

  if (currentQuestionIndexComplete < completeQuestions.length) {
    renderCompleteQ();
  } else {
    alert('所有题目完成！');
    showResult();
  }
}

// 补全题提交按钮事件
submitBtnComplete.addEventListener('click', function () {
  const currQ = completeQuestions[currentQuestionIndexComplete];
  const inputs = document.querySelectorAll('.complete-input');
  const userAnswers = [];
  let hasEmpty = false;

  // 收集用户答案并检查是否有未填写的
  inputs.forEach(inp => {
    const val = inp.value.trim().toLowerCase();
    if (!val) hasEmpty = true;
    userAnswers.push(val);
  });

  if (hasEmpty) {
    alert('请补全所有空！');
    return;
  }

  clearInterval(window.completeTimer);
  let isRight = true;
  const correctAnswers = [];

  // 逐个比对每个空的答案
  currQ.blanks.forEach((blank, index) => {
    correctAnswers.push(blank.correctChar);
    if (userAnswers[index] !== blank.correctChar) {
      isRight = false;
    }
  });

  if (isRight) {
    const add = currentQuestionIndexComplete >= 3 && currentQuestionIndexComplete % 4 === 3 ? 5 : 3;
    const currScore = parseInt(score.innerHTML) + add;
    score.innerHTML = currScore;

    const uname = document.querySelector('#input-username').textContent.trim();
    const scoreRecords = JSON.parse(localStorage.getItem('userScores') || '{}');
    // 直接计算总分数
    const totalScore = (scoreRecords[uname]?.totalScore || 0) + add;
    scoreRecords[uname] = {
      completeScore: currScore,
      totalScore: totalScore,
      lastUpdate: new Date().toLocaleString()
    };
    localStorage.setItem('userScores', JSON.stringify(scoreRecords));
    alert('正确！');

    
  } else {
    const correctStr = correctAnswers.join("");
    const userStr = userAnswers.join("");
    alert(`错误！正确答案应为：${correctStr}`);
    wrongQuestionList.push({
      type: "补全题",
      question: currQ.question,
      userAnswer: userStr,
      correctAnswer: correctStr
    });
  }

  nextCompleteQ();
});

// 填空题完成后进入补全题（补充定义）
function nextFillQuestion() {
  if (window.fillCountdownTimer) clearInterval(window.fillCountdownTimer);
  currentQuestionIndexFill++;
  if (currentQuestionIndexFill < fillQuestions.length) {
    renderCurrentFillQuestion();
  } else {
    alert('填空题完成！进入补全题');
    document.querySelector('.fill-question').style.display = 'none';
    document.querySelector('.complete-question').style.display = 'block';
    score.innerHTML = 0;
    document.querySelector('#timeRemaining').innerHTML = 30;
    generateCompleteQuestions();
    renderCompleteQ();
  }
}


// 结果页与错题回顾逻辑
function showResult() {
  const uname = document.querySelector('#input-username').textContent.trim();
  const scoreRecords = JSON.parse(localStorage.getItem('userScores') || '{}');
  // 直接取 totalScore
  const total = scoreRecords[uname]?.totalScore || 0;

  document.getElementById('result-username').textContent = uname;
  document.getElementById('result-score').textContent = `${total} 分`;
  document.getElementById('result-streak').textContent = '0 次';

  const rankList = document.getElementById('rank-list');
  rankList.innerHTML = '';
  Object.entries(scoreRecords)
    .sort((a, b) => (b[1].totalScore || 0) - (a[1].totalScore || 0))
    .forEach(([user, data], idx) => {
      const li = document.createElement('li');
      li.className = `rank-item ${idx < 3 ? `top-${idx + 1}` : ''}`;
      li.innerHTML = `
        <div class="rank-number">${idx + 1}</div>
        <div class="rank-username">${user}</div>
        <div class="rank-score">${data.totalScore || 0} 分</div>
      `;
      rankList.appendChild(li);
    });

  document.querySelector('.box').style.display = 'none';
  document.querySelector('.result-board').style.display = 'block';
}

// 结果页按钮逻辑（查看错题）
document.getElementById('restart-btn').addEventListener('click', () => {
  document.querySelector('.result-board').style.display = 'none';
  const wrongListEl = document.querySelector('.wrong-list');
  wrongListEl.innerHTML = '';

  if (wrongQuestionList.length === 0) {
    wrongListEl.innerHTML = '<p style="text-align:center; color:#666;">恭喜！本次答题全对，无错题~</p>';
  } else {
    wrongQuestionList.forEach((wrong, index) => {
      const wrongItem = document.createElement('div');
      wrongItem.className = 'wrong-item';
      wrongItem.innerHTML = `
        <p>${index + 1}. 【${wrong.type}】${wrong.question}</p>
        <p>你的答案：${wrong.userAnswer}</p>
        <p>正确答案：${wrong.correctAnswer}</p>
      `;
      wrongListEl.appendChild(wrongItem);
    });
  }

  document.querySelector('.wrong-questions').style.display = 'block';
});

// 错题页返回结果按钮
document.getElementById('back-to-result').addEventListener('click', () => {
  document.querySelector('.wrong-questions').style.display = 'none';
  document.querySelector('.result-board').style.display = 'block';
});
//去除广告
setTimeout(() => {
  let el = document.querySelector('p[align="center"]');
  if (el) el.remove();
}, 100)